-- FUNCTION: public.widget_PieChart_Lab_Revenue(date, text,integer,integer)

-- DROP FUNCTION IF EXISTS public."widget_PieChart_Lab_Revenue"(date, text,integer,integer);

CREATE OR REPLACE FUNCTION public."widget_PieChart_Lab_Revenue"(
	"fromDate" date,
	"filterType" text,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
intervaldata interval;
ftype text;
currentdate date;
fromdate date;
begin
intervaldata:= case when "filterType"='day' then '1 D' when "filterType"='month' then '1 Month' when "filterType"='year' then '1 Year' end;
ftype:= case when "filterType"='day' then 'month'::text  when "filterType"='month' then 'year'::text when "filterType"='year' then 'year'::text end;
currentdate:= case when  "filterType"='year' then date_trunc(ftype, "fromDate")  - '2 Y'::interval else date_trunc(ftype, "fromDate") end ;
fromdate:=case when "filterType"='day' and  current_date > "fromDate"  then   (date_trunc('month', "fromDate"::date) + interval '1 month' - interval '1 day')::date
 when  "filterType"='month' and   "fromDate" < current_date then  date_trunc('Year', "fromDate"::date) + interval '1 Year' - interval '1 month' 
 
else "fromDate" end;

 raise notice 'intervaldata %', intervaldata;
 raise notice 'ftype %', ftype;
  raise notice 'currentdate %', currentdate;
create  Temp TABLE temp_table 
( startdate date,
   enddate date,  
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 
for f in 
 select   generate_series( currentdate  , fromdate,  intervaldata)  weeks 
    loop 
	raise notice 'currentdate %', f.weeks::text::date;
	raise notice 'fromdate %', fromdate::date;
	insert into temp_table (startdate,enddate,countdata)
	
	select date_trunc('month', current_date)::date startdate ,f.weeks enddate,coalesce(sum(coalesce(ar."NetAmount",0)),0) "LabAmount" 
from "LabBookingHeader" ar 
left join "Provider" pr on pr."ProviderId"= ar."ProviderId"
left join "ProviderLocation" PL on PL."ProviderId"=pr."ProviderId" and case when "locationId" is null then 1=1 else  PL."LocationId"= "locationId" end

left join "Account" PA on PA."ReferenceId"=pr."ProviderId"  and PA."RoleId"=3
where ar."Active" <> false and (ar."CreatedDate"::date >= f.weeks::text::date and ar."CreatedDate"::date < (f.weeks+ intervaldata)::text::date)
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
and case when ("referenceId" is null) or ("referenceId"=0) then 1=1 else PA."ReferenceId"= "referenceId" end
;	
   
    end loop;
	RETURN QUERY
	select A.enddate,A.countdata from temp_table A;
	drop table temp_table;
END;
$BODY$;

ALTER FUNCTION public."widget_PieChart_Lab_Revenue"(date, text,integer,integer)
    OWNER TO postgres;